<template>
  <div class="product-container" :class="rootElementClassNames" v-loading.fullscreen.lock="loadingPage" >
    <div id="product-product-edit"></div>
    <div class="base-form bbx-normal-page-content" v-if="init" >

      <product-edit-form
        :fields="productFields"
        :is-edit="isEdit"
        v-model="form"
        :product-id="productId"
        :pending='pending'
        @submit='submit'
        @getBind="getBind"
        :hasReturn="!registerId"
        ref="productEditForm"
      >
      </product-edit-form>


      <!-- <div class="normal-btn-box mar-l-20">
        <el-button type="primary" @click="submitChooseQrcode" :loading="pending" class="btn btn-primary ">
          保存并关联二维码
        </el-button>
        <el-button @click="submit" :loading="pending">
          仅保存
        </el-button>

      </div> -->
    </div>

    <public-dialog :product-id="productId" :dialog-type="'linkQrcode'" @dialogBind="dialogBind" ref="publicDialog"/>
  </div>
</template>

<script>
/* api */
import {
  getProductFields,
  getProductDetail,
  createProduct,
  updateProduct,
  getRegisterValue
} from '@src/api/ProductApi'
/* component */
import ProductEditForm from '@src/modules/product/components/ProductEditFormV2.vue';
import PublicDialog from '@src/modules/productV2/productView/components/PublicDialog.vue';
/* enum */
import TenantDataLimitSourceEnum from '@model/enum/TenantDataLimitSourceEnum.ts'
import TenantDataLimitTypeEnum from '@model/enum/TenantDataLimitTypeEnum.ts'
import { ProductFieldNameMappingEnum } from '@model/enum/FieldMappingEnum.ts'
import ComponentNameEnum from '@model/enum/ComponentNameEnum.ts'
/* mixin */
import VersionMixin from '@src/mixins/versionMixin/index.ts'
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
/* util */
import * as util from '@src/modules/product/utils/ProductMapping';
import * as FormUtil from '@src/component/form/util';
import initData from '@src/modules/productV2/productEdit/initData.js'
import { storageGet, storageSet } from '@src/util/storage';
import { isEmpty } from '@src/util/type'
import { findComponentDownward } from '@src/util/assist'
import { scrollIntoFirstRequireDom } from '@src/util/dom';
import moment from 'moment';
/* service */
import { existsField, getFieldIsNull } from '@service/FieldService.ts'
/* constants */
import { PRODUCT_PRODUCT_EDIT } from '@src/component/guide/productV2Store'
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
/* mixin */
import { ConnectorModuleConnectorCreateProductMixin } from '@src/modules/connector'
import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormSubmitTime, disposeFormViewTime } = useFormTimezone()
/* version control mixin */
import { VersionControlProductMixin } from '@src/mixins/versionControlMixin'
import { hasBSCEnterpriseEdition } from '@src/util/version'
import { 
  getQualityStartTimeField,
  getQualityEndTimeField,
} from '@src/component/form/components/FormQualityInfoField/FormQualityInfoModel'

import addressKeyToViewLanguage, { getCountryKey } from '@src/component/common/BaseAddressSwitch/addressNameMultiLanguage';
function duibi (registerRes,obj){
   function fuzhi(a, b){
    if(b){
      if(!obj[a])
       obj[a] ={}
      obj[a][b] = registerRes[a][b]
    }
    obj[a] = registerRes[a]
  }
  for(let i in registerRes){
    if(registerRes[i] instanceof Object){ // 对象
      let attribute = registerRes[i]
      for(let ii in attribute){
        if(attribute[ii] instanceof Array){ // 数组并且有值
          if(attribute[ii].length){
            fuzhi(i,ii)
          }
        }else{ // 除了数组和对象之外的
          if(attribute[ii])
            fuzhi(i,ii)
        }
      }
    }else{
      if(registerRes[i] instanceof Array){ // 数组并且有值
        if(registerRes[i].length){
          fuzhi(i)
        }
      }else{ // 除了数组和对象之外的
        if(registerRes[i])
          fuzhi(i)
      }
    }
  }
  return obj
}

export default {
  name: 'product-edit',
  mixins: [
    VersionMixin,
    ThemeMixin,
    ConnectorModuleConnectorCreateProductMixin,
    VersionControlProductMixin
  ],
  provide() {
    return{
      // initData,
      cloneProduct: this.cloneProduct,
      isEdit: this.isEdit,
    }
  },
  inject: ['initData'],
  data() {
    return {
      radioBind:1,
      hasRepeatRepair:false,
      loadingPage: false,
      pending: false,
      init: false,
      submitting: false,
      form: {},
      // initData,
      dynamicProductFields: [],
      product: {}
    }
  },
  computed: {
    productFields() {

      const dynamicProductFields = this.dynamicProductFields.slice()
      // 只要有服务云企业版新建产品表单就隐藏选择模版
      if (!hasBSCEnterpriseEdition() && this._isShowProductTemplate) {
        dynamicProductFields.unshift({
          displayName: this.$t('product.type.template'),
          fieldName: 'template',
          formType: 'select',
          isSystem: 1
        })
      }

      return dynamicProductFields

    },
    auth() {
      return this.initData.auth || {};
    },
    productId() {
      // const matchRes = window.location.href.match(/customer\/product\/edit\/([\w-]*)(\??.*)/);
      return this.initData.id || '';
    },
    registerId() {
      // const matchRes = window.location.href.match(/customer\/product\/edit\/([\w-]*)(\??.*)/);
      return this.initData.registerId || '';
    },
    // 客户上创建产品会带一个cId
    customer() {
      return this.initData.customer || null;
    },
    action() {
      return this.productId ? 'edit' : 'create';
    },
    isEdit() {
      return this.action == 'edit'
    },
    isExistQualityInfoField() {
      return existsField(ProductFieldNameMappingEnum.QualityInfo, this.productFields)
    },
    isExistQualityInfoFieldIsNull() {
      return this.isExistQualityInfoField ? getFieldIsNull(this.isExistQualityInfoField) : true
    },
    isCatalogIdEmpty() {
      return isEmpty(this.form.catalogId)
    },
    isQualityInfoAuto() {
      return this.form?.qualityInfo?.isAutoComputed
    },
    isQualityInfoAutoStartTimeEmpty() {
      return isEmpty(this.form?.qualityInfo?.auto?.qualityInfoStartTime)
    },
    isQualityNotSubmitForm() {
      return (
        !this.isEdit
        && (this.isCatalogIdEmpty || this.formQualityBuildComponent.isQualityRuleTimeFieldDataEmpty)
        && this.isQualityInfoAuto
        && this.isQualityInfoAutoStartTimeEmpty
        && this.isExistQualityInfoField
        && !this.isExistQualityInfoFieldIsNull
      )
    },
    formQualityBuildComponent() {
      return findComponentDownward(this.$refs.productEditForm || {}, ComponentNameEnum.FormQualityInfoBuild) || {}
    },
    qualityInfoField() {
      return this.productFields.find(field=> field.formType === 'quality_info') || {}
    }  
  },
  async mounted() {
    try {
      // 获取产品自定义字段
      let res = await getProductFields({isFromSetting: true});
      this.dynamicProductFields = res.data || [];
      this.dynamicProductFields.forEach(field => {
        if (field.fieldName == 'isRepeatRepair') {
          this.hasRepeatRepair = true
        }
      })


      // 从paas新建产品的话 过滤掉产品
      if (this.$route.query?.from === 'paas') {
        this.dynamicProductFields = this.dynamicProductFields.filter(field => field.formType !== 'customer')
      }

      // 过滤不能编辑的自定义字段 不展示(是否重复报修)
      this.dynamicProductFields = this.dynamicProductFields.filter(field => field.setting?.isEdit != 0)
      // 产品编号限制字数最大长度为100
      this.dynamicProductFields.forEach(field => {
        if (field.fieldName == 'serialNumber') {
          field.maxlength = 100
        }
        if(field.formType == 'attachment' && !field.tips) {
          this.$set(field, 'tips', this.$t('product.form.tips.imageTip'));
        }
      })
    } catch (e) {
      console.error('product-add_edit fetch product fields error', e);
    }

    // 初始化默认值
    let form = {};
    if (this.action === 'edit') {
      // 处理编辑时数据
      this.loadingPage = true;
      let res = await getProductDetail({id: this.productId});

      if(res.address){
        const newAddress = await this.switchAddress(res.address);
        res.address = { ...res.address, ...newAddress }
      }
      
      this.loadingPage = false;
      if(res.id) {
        form = res
        this.product = res
      }
      if(this.registerId){
        let registerRes = await getRegisterValue({id: this.registerId, productId: this.productId});
        this.product = duibi(registerRes, this.product)
        form = duibi(registerRes, form)
      }
    } else {
      if(this.registerId){
        let registerRes = await getRegisterValue({id: this.registerId, productId: this.productId});
        this.product = duibi(registerRes, this.product)
        form = duibi(registerRes, form)
      }
      // 检查版本数量限制
      this.checkNumExceedLimitBeforeHandler
      && this.checkNumExceedLimitBeforeHandler(
        TenantDataLimitSourceEnum.Product,
        TenantDataLimitTypeEnum.Product
      )
    }
    // 处理富文本
    form = await FormUtil.initRichTextContent(this.productFields, form);

    form = util.packToForm(this.productFields, form, this.idEdit);

    // 客户详情新建产品，会带的客户信息
    if (this.customer) {
      form.customer = [{
        label: this.customer.name,
        value: this.customer.id,
        ...this.customer
      }];
    }

    /**
     * 初始化所有字段的初始值
     * @param {*} fields 字段
     * @param {*} origin 原始值
     * @param {*} target 待合并的值
     */
    this.form = disposeFormViewTime(this.productFields, FormUtil.initialize(this.productFields, form)); // 初始国际化时间
    if(this.isQualityInfoAuto && this.form?.qualityInfo?.auto?.qualityInfoEndTime) {
      // 结束日期修改
      this.form.qualityInfo.auto.qualityInfoEndTime = moment(this.form.qualityInfo.auto.qualityInfoEndTime).format('YYYY-MM-DD')
    }
    if (storageGet(PRODUCT_PRODUCT_EDIT) && storageGet(PRODUCT_PRODUCT_EDIT) > 0) this.$Guide().destroy('product-product-edit')
    else this.$Guide([{
      content: this.$t('product.form.tips.guideTip'),
      haveStep: false,
      nowStep: 1,
      id: 'product-product-edit',
      domId:'form-related-catalog',
      finishBtn: 'ok',
    }], 0, '', (e) => {
      return new Promise((resolve, reject) => {
        resolve()
      })
    }).create().then(res_=>{if(res_)storageSet(PRODUCT_PRODUCT_EDIT, '1')})

    this.init = true;

    // this.fetchConnectorInsertSelectCall()
  },
  beforeDestroy() {
    this.removeConnectorCreateSessionData()
  },

  methods: {
    // 编辑页面获取到的地址数据，需要翻译
    async switchAddress(address){
      let key = getCountryKey(address)

      let newAddress = await addressKeyToViewLanguage(key,address);
      return newAddress
    },
    getBind(val){
      this.radioBind=val
    },
    submit(createQrcode=false) {
      this.submitting = true;
      this.$refs.productEditForm.validate()
        .then(valid => {
          scrollIntoFirstRequireDom( this.$refs.productEditForm.$refs.form)
          this.submitting = false

          if (this.isQualityNotSubmitForm) {
            valid = false
          }

          if (!valid) {
            return Promise.reject('validate fail.')
          }

          this.form.id = this.productId

          let params = util.packToProduct(this.productFields, this.form, this.product)
          // 质保时间字段需要加下，不然不能处理到~
          params = disposeFormSubmitTime([
            ...this.productFields,
            getQualityStartTimeField(this.qualityInfoField),
            getQualityEndTimeField(this.qualityInfoField)
          ], params)

          if(params.qualityStartTime && params.qualityEndTime && moment(params.qualityEndTime).valueOf() < moment(params.qualityStartTime).valueOf()) {
            this.$platform.notification({
              title: '',
              message: this.$t('common.quality.qualityTips'),
              type: 'error',
            })
            return
          }

          params = this.globalFormSubmissionDataProcessingHandler(this.productFields, params)

          this.registerId && (params.registerId = this.registerId)

          // 添加默认是否重复报修
          if (this.action == 'create' && this.hasRepeatRepair) {
            params.attribute.isRepeatRepair = '否'
          }

          this.productFields.forEach(field =>{
            if(field.fieldName == 'customer' && field.isSystem == 1) {
              if (!field.setting?.customerOption?.address) {
                params.address = {}
              } else if (!field.setting?.customerOption?.linkman){
                params.linkman = {}
              }
            }
          })
          // 是否生成二维码
          if(createQrcode){
             params.createQrcode=createQrcode
           }

          params.hasBindCustomer = this.radioBind
          // 如果配置项关闭，则hasBindCustomer传参固定为1
          if (!this.$refs.productEditForm?.hasBindCustomer) {
            params.hasBindCustomer = 1
          }


          // 复制的时候新建也会有id，这边去掉
          params.id = this.action === 'create'?'':params.id


          // 从paas新建产品过来的话，自动复制customerId
          if (this.$route.query?.from === 'paas') {
            params.customerId = this.$route.query?.customerId

            if (this.$route.query?.addressId) {
              params.address.id = this.$route.query.addressId
            }
            if (this.$route.query?.linkmanId) {
              params.linkman.id = this.$route.query.linkmanId
            }
          }

          // 不关联客户的时候把客户相关的数据清空
          if(!params.hasBindCustomer){
            params.customerId=null
            params.address=null
            params.linkman=null
          }


          if (this.action == 'edit' && this.$refs.productEditForm?.needServerDeleFiles?.length) {
            params['deleteFiles'] = this.$refs.productEditForm?.needServerDeleFiles
          }

          this.toggleLoading(params)

          let fn = this.action === 'create' ? createProduct : updateProduct

          try {
            this.setConnectorParamsForSubmit(params)
          } catch (error) {
            console.error(error)
          }

          this.checkNumExceedLimitAfterHandler(fn(params))
            .then(res => {
              const tips = {
                createSuccess: this.$t('product.form.tips.tip1'),
                createFail: this.$t('product.form.tips.tip2'),
                updateSuccess: this.$t('product.form.tips.tip3'),
                updateFail: this.$t('product.form.tips.tip4'),
              }

              if (!res.succ) {
                this.toggleLoading(false)
                return this.$platform.notification({
                  title: this.action === 'create' ? tips.createFail : tips.updateFail,
                  message: res.message || '',
                  type: 'error',
                })
              }

              this.$refs.publicDialog.close()

              this.$platform.notification({
                title: this.action === 'create' ? tips.createSuccess : tips.updateSuccess,
                type: 'success',
              })

              let sendPaasProductParams = {
                ...params,
                typeId: params.catalogId,
                id: res.data,
                productId: res.data, // 接口返回的产品id
                catalogId: this.form.catalogId?.label || ''
              }

              if (this.$route.query?.from === 'paas') {
                let message = {
                    action: 'shb.create.customer.product',
                    data: sendPaasProductParams,
                    fromId: window.frameElement.getAttribute('fromid')
                };
                  window.parent.postMessage(message, '*')

                  console.log(message, 'message从新建产品提交的')
                  let id = window.frameElement.dataset.id;
                  this.$platform.closeTab(id);
              } else {
                if (this.customer) {
                  this.closeAndOpenTab('PageCustomerView' ,this.customer.id)
                } else {
                  let fromId = window.frameElement.getAttribute('fromid')
                  this.$platform.refreshTab(fromId)

                  this.closeAndOpenTab('PageProductView', res.data)
                }
              }
              this.removeConnectorCreateSessionData()
            })
            .catch(err => {
              console.error(err);
              this.toggleLoading(false)
            })
            .finally(()=>{
              this.$refs.publicDialog.changeLoading(false);
            })
        })
        .catch(err => {
          console.error(err);
          this.toggleLoading(false)
        })
    },

    dialogBind(e){
      this.form['qrcodeId'] = e.qrcodeId;
      this.submit();
    },
    goBack() {
      if(this.action == 'create') {
        let id = window.frameElement.dataset.id;
        return this.$platform.closeTab(id);
      }
      parent.frameHistoryBack(window);
    },
    reloadTab() {
      let fromId = window.frameElement.getAttribute('fromid');
      this.$platform.refreshTab(fromId);
    },
    async cloneProduct(id){
      let form = {};
      // 处理编辑时数据
      this.loadingPage = true;
      let res = await getProductDetail({id});

      this.loadingPage = false;
      if(res.id) {
        form = res;
      }
      form = util.packToForm(this.productFields, form);

      // 客户详情新建产品，会带的客户信息
      if (this.customer) {
        form.customer = [{
          label: this.customer.name,
          value: this.customer.id,
          ...this.customer
        }];
      }
      /**
       * 初始化所有字段的初始值
       * @param {*} fields 字段
       * @param {*} origin 原始值
       * @param {*} target 待合并的值
       */
      this.form = FormUtil.initialize(this.productFields, form)
      this.product.qualityCalculation = res?.qualityCalculation
      // 复制产品信息 初始化产品类型
      if(this.form['catalogId'] && res.catalogId) {
        this.$nextTick(() => {
          console.log(res, '初始化的数据')
          this.$refs.productEditForm.catalogInput([res.catalogId])
        })
      }
    },
    toggleLoading(loading = true) {
      this.pending = loading
      this.loadingPage = loading
    },

    closeAndOpenTab(type, id) {

      try {

        const isInFrame = this.validateCurrentWindowIsInFrame()

        if (isInFrame) {
          this.postCloseDialogMessage()
          return
        }

      } catch (error) {
        console.error(error)
      }

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        fromId,
        type:PageRoutesTypeEnum[type],
        key:id,
        closeNowPage:true
      });
    },
  },
  components: {
    [ProductEditForm.name]: ProductEditForm,
    [PublicDialog.name]:PublicDialog
  }
}
</script>

<style lang="scss">
body {
  padding: 12px;
}

.product-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #fff;
  border-radius: 4px;

  .product-edit-form {
    height: 100%;
  }

  .page-title {
    border-bottom: 1px solid #f4f7f5;
    padding: 12px 10px;
    display: flex;
    justify-content: space-between;

    .iconfont {
      font-size: 12px;
    }

    .title {
      display: flex;
      justify-content: space-between;
      span.text {
        line-height: 34px;
        margin-right: 12px;
      }
    }
  }
}

.form-builder-container {
  height: calc(100% - 56px);
  margin: 0 auto;
  padding: 10px 16px;
  overflow: auto;
}
.form-builder-container-cell{
  padding: 24px 20px 24px 32px;
  .form-builder{
    padding: 0;
  }
}
.form-builder {
  .input-and-btn {
    display: flex !important;
    flex-flow: row nowrap;

    .form-item,
    .form-text,
    .form-select,
    .biz-team-select {
      flex: 1;
    }

    .base-dist-picker {
      padding-right: 0;
    }

    button {
      margin-left: 10px;
    }
  }
}
</style>
